const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 配置存储
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // 根据文件类型设置不同的存储目录
        let uploadPath = 'public/uploads/';
        if (file.mimetype.startsWith('image/')) {
            uploadPath += 'images/';
        } else if (file.mimetype.startsWith('video/')) {
            uploadPath += 'videos/';
        } else {
            uploadPath += 'others/';
        }

        // 确保目录存在
        fs.mkdirSync(uploadPath, { recursive: true });
        cb(null, uploadPath);
    },
    filename: function (req, file, cb) {
        // 生成文件名: 时间戳 + 随机数 + 原始扩展名
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, uniqueSuffix + path.extname(file.originalname));
    }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
    // 允许的文件类型
    const allowedTypes = [
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/webp',
        'video/mp4',
        'video/webm'
    ];

    if (allowedTypes.includes(file.mimetype)) {
        cb(null, true);
    } else {
        cb(new Error('不支持的文件类型'), false);
    }
};

// 创建 multer 实例
const upload = multer({
    storage: storage,
    fileFilter: fileFilter,
    limits: {
        fileSize: 1000 * 1024 * 1024, // 限制文件大小为 1g
    }
});

// 单文件上传路由
router.post('/single', upload.single('file'), (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({ error: '没有文件被上传' });
        }

        // 返回文件信息
        res.json({
            message: '文件上传成功',
            file: {
                filename: req.file.filename,
                originalname: req.file.originalname,
                mimetype: req.file.mimetype,
                size: req.file.size,
                path: req.file.path.replace('public', ''), // 转换为URL路径
                url: `/public/uploads/${path.basename(path.dirname(req.file.path))}/${req.file.filename}` // 完整URL
            }
        });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 多文件上传路由
router.post('/multiple', upload.array('files', 5), (req, res) => {
    try {
        if (!req.files || req.files.length === 0) {
            return res.status(400).json({ error: '没有文件被上传' });
        }

        // 返回所有文件信息
        const files = req.files.map(file => ({
            filename: file.filename,
            originalname: file.originalname,
            mimetype: file.mimetype,
            size: file.size,
            path: file.path.replace('public', ''),
            url: `/uploads/${path.basename(path.dirname(file.path))}/${file.filename}`
        }));

        res.json({
            message: '文件上传成功',
            files: files
        });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

module.exports = router;